package tut.Struct.collection.phan1.map.weakHashMap.weakHashMapvsHashMap;

import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapDemo {

  public static void main(String[] args) {

      //add one element to the map...
      Map<Data, String> map  = new WeakHashMap<Data, String>();
      Data someDataObject = new Data("test");
      map.put(someDataObject, someDataObject.value);
      System.out.println("map contains someDataObject ? " + map.containsKey(someDataObject));

      //now make someDataObject eligible for garbage collection...
      someDataObject = null;

      for (int i = 0; i < 1000000; i++){
          if(map.size()!=0)
          {
              System.out.println("At iteration " + i + " the map still holds the reference on someDataObject");
          }
          else
          {
              System.out.println("someDataObject has finally been garbage collected at iteration " + i + ", so the map is now empty");
              break;
          }

      }
  }

  static class Data{
      String value;
      Data(String value){
          this.value = value;
      }
  }
}
